//
//  popView
//  coverFlow
//
//  Created by kal on 13-1-10.
//  Copyright (c) 2013年 warlee. All rights reserved.
//

#import "PopView.h"


@implementation PopView
@synthesize delegate;
@synthesize thisView;
@synthesize gesture;
@synthesize isbackground;
@synthesize isBackgroundClick;
@synthesize popViewAt;
@synthesize popViewAnimationFrom;
@synthesize backgroundColor;
@synthesize flipFromView;
@synthesize fromFrame;
@synthesize toFrame;

static int popViewCount = 0;

- (id)init{
    self = [super init];
    if (self) {
        isbackground         = YES;
        isBackgroundClick    = YES;
        isRunning            = NO;
        popViewAt            = PopViewAtRight;              //定位位置
        popViewAnimationFrom = PopViewAnimationFromRight;   //动画方式
        backgroundColor      = RGB(0, 0, 0);
    }
    return self;
}
//继承该对象时可初始化view
- (void)setView{
    popWidth            = self.thisView.frame.size.width;
    popHeight           = self.thisView.frame.size.height;
    fromFrame           = CGRectMake(-1, -1, popWidth, popHeight);
    toFrame             = CGRectMake(0, 0, popWidth, popHeight);
}


//拨动手势，用于view的拖拽
- (void)initGesture{
    gesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(move:)];
    [self.thisView addGestureRecognizer:gesture];
    //[gesture setDelegate:self];
}
-(void)move:(id)sender {
    //CGPoint thisPoint = [(UIPanGestureRecognizer*)sender translationInView:self.thisView];
    //NSLog(@"x=%f,y=%f,s=%d",thisPoint.x,thisPoint.y,gesture.state);
}


// 添加popView，需要传入父视图；添加时，用popViewCount做数量标记；
- (void)addView:(UIView *) theView{
    isRunning = YES;
    popViewCount ++;
    superViewFrame = theView.bounds;
    if (popViewCount == 1) {
        popMainView = [[UIView alloc] initWithFrame:superViewFrame];
        [theView addSubview:popMainView];
        
        popMaskView  = [[UIView alloc] initWithFrame:superViewFrame];
        [popMaskView setTag: TAG_OFFSET_BACKGROUND];
        if (isbackground) {
            popMaskView.backgroundColor = backgroundColor;
            popMaskView.alpha = 0;
        }
        [popMainView addSubview:popMaskView];
        if (isBackgroundClick) {
            UIButton *backgroundButton = [UIButton buttonWithType:UIButtonTypeCustom];
            backgroundButton.frame = superViewFrame;
            backgroundButton.backgroundColor = [UIColor clearColor];
            //触发到函数
            [backgroundButton addTarget:self action:@selector(closePopAll:) forControlEvents:UIControlEventTouchUpInside];
            [popMainView addSubview:backgroundButton];
        }
    }else{
        popMaskView = [theView viewWithTag:TAG_OFFSET_BACKGROUND];
        popMainView = popMaskView.superview;
    }
    [self initFrame];
    
    //动画效果
    [self.thisView setFrame:fromFrame];
    [self.thisView setTag:TAG_OFFSET_POP_VIEW+popViewCount];
    [popMainView addSubview:self.thisView];
    if (popViewAnimationFrom == PopViewAnimationFromFlip) { //flip  动画
        if (fromFrame.origin.x == -1) {
            fromFrame = flipFromView.frame;
        }
        toFrame.origin.x     = (superViewFrame.size.width - popWidth)/2;
        toFrame.origin.y     = (superViewFrame.size.height - popHeight)/2;
        CGRect  middleFrame  = CGRectMake((toFrame.origin.x + fromFrame.origin.x)/2,
                                          (toFrame.origin.y + fromFrame.origin.y)/2,
                                          popWidth/2, popHeight/2);
        self.thisView.alpha  = 0;
        flipImageView        = [[UIView alloc] initWithFrame:fromFrame];
        UIImage *screenshot  = [self screenshot:flipFromView];
        flipImageView.layer.contents = (id)screenshot.CGImage;
        [popMainView addSubview:flipImageView];
        
        [UIView animateWithDuration:POP_ANIMATE_TIME/3 animations:^{
            [flipImageView setFrame:middleFrame];
            flipImageView.layer.transform = [self _flip3D:90.0f*[self getCnner]];
        }completion:^(BOOL finished) {
            [self updateTextView];
            [thisView setFrame:middleFrame];
            [thisView setAlpha:1];
            thisView.layer.transform = [self _flip3D:-90.0f*[self getCnner]];
            [flipImageView setAlpha:0];
            [UIView animateWithDuration:POP_ANIMATE_TIME/3 animations:^{
                thisView.layer.transform = [self _flip3D:0.0f];
                [thisView setFrame:toFrame];
            }completion:^(BOOL finished) {
                isRunning = NO;
                [UIView animateWithDuration:POP_ANIMATE_TIME/3 animations:^{
                    if(popViewCount == 1 && isbackground) popMaskView.alpha = 0.5;
                }completion:^(BOOL finished) {}];
            }];
        }];
    }else {
        [UIView animateWithDuration:POP_ANIMATE_TIME animations:^{
            if(popViewCount == 1 && isbackground) popMaskView.alpha = 0.5;
            self.thisView.alpha = 1;
            [self.thisView setFrame:toFrame];
        }completion:^(BOOL finished) {
            isRunning = NO;
        }];
    }
}
-(int)getCnner{
    return (fromFrame.size.width/2 + fromFrame.origin.x)>512 ? -1:1;
}
-(void)initFrame{
    switch (popViewAnimationFrom) {
        case PopViewAnimationFromRight:
            fromFrame.origin.x   = superViewFrame.size.width;
            fromFrame.origin.y   = (superViewFrame.size.height - popHeight)/2;
            break;
        case PopViewAnimationFromLeft:
            fromFrame.origin.x   = - superViewFrame.size.width;
            fromFrame.origin.y   = (superViewFrame.size.height - popHeight)/2;
            break;
        case PopViewAnimationFromTop:
            fromFrame.origin.x   = (superViewFrame.size.width - popWidth)/2;
            fromFrame.origin.y   = - popHeight;
            break;
        case PopViewAnimationFromBottom:
            fromFrame.origin.x   = (superViewFrame.size.width - popWidth)/2;
            fromFrame.origin.y   = superViewFrame.size.height;
            break;
        case PopViewAnimationFromFadeIn:
            fromFrame.origin.x   = (superViewFrame.size.width - popWidth)/2;
            fromFrame.origin.y   = (superViewFrame.size.height - popHeight)/2;
            fromFrame.size.width = popWidth;
            fromFrame.size.height= popHeight;
            self.thisView.alpha  = 0;
            break;
        case PopViewAnimationFromToBig:
            fromFrame.origin.x   = superViewFrame.size.width/2;
            fromFrame.origin.y   = superViewFrame.size.height/2;
            fromFrame.size.width = 0;
            fromFrame.size.height= 0;
            self.thisView.alpha  = 0;
            break;
        case PopViewAnimationFromToSmall:
            fromFrame.origin.x   = 0;
            fromFrame.origin.y   = 0;
            fromFrame.size.width = superViewFrame.size.width;
            fromFrame.size.height= superViewFrame.size.height;
            self.thisView.alpha  = 0;
            break;
        default:break;
    }
    switch (popViewAt) {
        case PopViewAtRight:
            toFrame.origin.x     = superViewFrame.size.width - popWidth;
            toFrame.origin.y     = (superViewFrame.size.height - popHeight)/2;
            break;
        case PopViewAtLeft:
            toFrame.origin.x     = 0;
            toFrame.origin.y     = (superViewFrame.size.height - popHeight)/2;
            break;
        case PopViewAtTop:
            toFrame.origin.x     = (superViewFrame.size.width - popWidth)/2;
            toFrame.origin.y     = 0;
            break;
        case PopViewAtBottom:
            toFrame.origin.x     = (superViewFrame.size.width - popWidth)/2;
            toFrame.origin.y     = superViewFrame.size.height - popHeight;
            break;
        case PopViewAtMiddle:
            toFrame.origin.x     = (superViewFrame.size.width - popWidth)/2;
            toFrame.origin.y     = (superViewFrame.size.height - popHeight)/2;
            toFrame.size.width   = popWidth;
            toFrame.size.height  = popHeight;
            self.thisView.alpha  = 0;
            break;
        default:break;
    }
}



//3d 变换下，textView抽风地不显示文字了，需要手动拖动才显示。
-(void)updateTextView{
    for (id temp in thisView.subviews) {
        if ([temp isKindOfClass:[UITextView class]]) {
            UITextView * tempTextView = (UITextView *)temp;
            NSString * tempText = [NSString stringWithString:tempTextView.text];
            tempTextView.text = nil;
            tempTextView.text = tempText;
        }
    }
}

//3d 变换参数
-(CATransform3D)_flip3D:(CGFloat)conner{
    CATransform3D flip3D= CATransform3DIdentity;
    flip3D.m34 = 1.0 / -500;    //透视效果，近大远小;该设定一定要写在下面下面一行前面。只对z轴变化有效
    flip3D = CATransform3DRotate(flip3D,conner * M_PI / 180.0f, 0.0f, 1.0f, 0.0f);
    //flip3D  =CATransform3DTranslate(flip3D,conner * M_PI / 180.0f, 0.0f,100);    
    return flip3D;
}

- (UIImage *)screenshot:(UIView *)fromView{
	UIGraphicsBeginImageContext(fromView.bounds.size);
	[[UIColor clearColor] setFill];
	[[UIBezierPath bezierPathWithRect:fromView.bounds] fill];
	CGContextRef ctx = UIGraphicsGetCurrentContext();
	[fromView.layer renderInContext:ctx];
	UIImage *anImage = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	return anImage;
}

//关闭popView，从父视图删除
- (void)closeView{
    if (isRunning) return;    
    popViewCount -- ;
    if (popViewAnimationFrom == PopViewAnimationFromFlip) {
        CGRect  middleFrame  = CGRectMake((toFrame.origin.x + fromFrame.origin.x)/2,
                                (toFrame.origin.y + fromFrame.origin.y)/2,popWidth/2, popHeight/2);
        [UIView animateWithDuration:POP_ANIMATE_TIME/3 animations:^{
            if(popViewCount == 0 && isbackground) popMaskView.alpha = 0;
        }completion:^(BOOL finished) {
            [UIView animateWithDuration:POP_ANIMATE_TIME/3 animations:^{
                [thisView setFrame:middleFrame];
                thisView.layer.transform = [self _flip3D:-90.0f*[self getCnner]];
            }completion:^(BOOL finished) {
                [flipImageView setAlpha:1];
                flipImageView.layer.transform = [self _flip3D:90.0f*[self getCnner]];
                [UIView animateWithDuration:POP_ANIMATE_TIME/3 animations:^{
                    flipImageView.layer.transform = [self _flip3D:0.0f];
                    [flipImageView setFrame:fromFrame];
                }completion:^(BOOL finished) {
                    [self.thisView removeFromSuperview];
                    [flipImageView removeFromSuperview];
                    if (popViewCount <= 0)  [popMaskView.superview removeFromSuperview];
                    [self clear];
                }];
            }];
        }];
    }else {
        [UIView animateWithDuration:POP_ANIMATE_TIME animations:^{
            if (popViewCount < 1 && isbackground)  popMaskView.alpha = 0;
            self.thisView.alpha = 0;
            [self.thisView setFrame:fromFrame];
        }completion:^(BOOL finished) {
            [self.thisView removeFromSuperview];
            if (popViewCount <= 0) {
                [popMaskView.superview removeFromSuperview];
            }
            [self clear];
        }];
    }
}
//关闭所有，遍历popView 将所有下层的先移除，再用动画方式移除最上面的
- (void)closeAll{
    if (isRunning) return;
    
    for (int i = 0; i<=popViewCount; i++) {
        if (self.thisView.tag != i+TAG_OFFSET_POP_VIEW+1) {
            [[self.thisView.superview viewWithTag:i+TAG_OFFSET_POP_VIEW+1] removeFromSuperview];
        }
    }
    popViewCount = 1;
    [self closeView];
}
- (IBAction)closePopAll:(id)sender {
    [self closeAll];
}
-(void)clear{
    [delegate PopViewDidClose];
    [self setBackgroundColor:nil];
    [self setFlipFromView:nil];
    [self setGesture:nil];
    [self setThisView:nil];
}
@end
